require([
    'jquery',
    'masonry', 
    'imagesloaded',
    'jquery-bridget/jquery.bridget',
    'module/handlebars',
    'global',
    'underscore',
    'zeroclipboard',
    'bootstrap',
    'jquery.debounce',
    'jquery.scrollto',
    'requirejs/domready!'], 
function($, Masonry, ImagesLoaded, bridget, handlebars, g, _, ZeroClipboard) {
	
	var products = [];
	var filters = {};
	var modelId = $('#model-id-marker').data('id');
	var category = $('#category-marker').data('id');
	var zcb = new ZeroClipboard();
	var total = 0;
	var currentCn = 1;
	
	// make Masonry a jQuery plugin
	bridget( 'masonry', Masonry );
	
	$(window).resize($.debounce( 500, function(){
		var w = $('.container').width()-parseInt($('.main-content').css('margin-left'));
		$('.main-content').css('width', w);
		$('.filter-bar').css('width', w + 2);
		setTimeout(function(){
			$('.masonry-container').masonry();
		}, 500);
	}));
	
	var filterProducts = function (cn, clear){
		
		// filer the options behind the clicked
		var fs = _.filter(
				_.values(filters), 
				function(item){
					return item.categoryNumber <= cn;
				}
			);
		// rebuild the filters
		filters = {};
		_.each(fs, function(item){
			filters[item.categoryNumber] = item;
		});
		
		var p, 
			filterIds = _.pluck(fs,'id'),
			filteredProducts = [],
			featureIds = [];
		for(var i=0; i<products.length;i++){
			p = products[i];
			featureIds = _.pluck(p.features, 'id');
			if(_.isEmpty(filterIds) || _.isEmpty(_.difference(filterIds, featureIds))){
				filteredProducts.push(p);
			}
		}
		updateFilterBar(cn, filteredProducts, clear);
		handlebars.getTemplate('product-pins')
			.done(function(tmpl){
				var pins = tmpl({products: filteredProducts, context:g.context, modelId: modelId}),
				$pins = $(pins).find('.item');
				$('.masonry-container')
					.masonry('remove', $('.masonry-container .item'))
					.append( $pins )
					.masonry( 'appended', $pins)
					.masonry();
			});
	};
	
	var updateFilterBar = function(cn, pds, clear){
		if(cn < total){
			var targets = $('.filter-bar')
				.find('.dropdown[data-categorynumber="'+cn+'"]')
				.nextAll();
			var next = targets.filter(function(idx){
				return idx === 0;
			});
			targets.each(function(){
				$(this).find('span:first-child').text($(this).data('label'));
			});
			targets.find('> .dropdown-menu').empty();
			targets.find('> button').prop('disabled', true);
			
			if(!clear){
				var fls = _.flatten(
						_.pluck(pds, 'features'), true);
				
				var fs = _.filter(
							_.uniq(fls,
								false,
								function(item){
									return item.id;
								}), 
							function(item){
								return item.categoryNumber == cn+1;
							});
				$.when(handlebars.getTemplate('product-filters-item'))
					.done(function(tmpl3){
						next.find('> .dropdown-menu').append(tmpl3(fs));
						next.find('> button').prop('disabled', false);
						currentCn = cn;
					});
			}else{
				currentCn = Math.max(1,cn-1);
			}
		}
	};
	
	var getProducts = function(vmId){
		$.when($.getJSON(g.context + '/models/'+vmId + '/products?category=' + (category || 'cover')), 
				handlebars.getTemplate('product-pins'),
				handlebars.getTemplate('product-filters'),
				handlebars.getTemplate('product-filters-item'))
			.done(function(defer, tmpl, tmpl2, tmpl3){
				var data = defer[0].data;
				products = data.products;
				total = _.keys(data.map).length;
				var filters = tmpl2(data);
				var categoryName = ($('.category-nav .nav-tabs > li.active a').text() || '').replace('汽车','');
				$('.filter-bar').empty().append(filters);
				if(data.map && data.map['1']){
					var filter1 = tmpl3(data.map['1']);
					var dp = $('.filter-bar').find('.dropdown[data-categorynumber="1"]');
					dp.find('> button').prop('disabled', false);
					dp.find('> .dropdown-menu').append(filter1);
				}
				var pins = tmpl($.extend({}, data, {context:g.context, modelId: modelId, categoryName: categoryName})),
					$pins = $(pins).find('.item');
				// ensure that images load before adding to masonry layout
				new ImagesLoaded($pins, function(){
					// show elems now they're ready
					$('.masonry-container')
						.masonry('remove', $('.masonry-container .item'))
						.append( $pins )
						.masonry( 'appended', $pins)
						.masonry();
				});
				zcb.clip($pins.find('.copy-btn'));
			});
	};
	
	if( modelId ){
		
//		var zcb = new ZeroClipboard();
//		
//		$('.main-content').on('click', '.copy-btn', function(){
//			var id = $(this).parents('.thumbnail.item')
//					.find('.caption .label-warning').text();
//			ZeroClipboard.setData( "text/plain", id );
//		});
		
		$('.masonry-container').masonry({
			itemSelector: '.item',
			gutter: '.gutter',
			isResizeBound: false
		});
		
		$('.filter-bar').on('click', '.dropdown-menu > li > a', function(){
			var $dp = $(this).parents('.dropdown');
			var label = $dp.data('label');
			var name = $(this).text(), 
				id = $(this).data('id'), 
				num = $dp.data('categorynumber'),
				clear = false;
			if(currentCn === num && 
					filters[num] && filters[num].name === name){
				return;
			}
			if(name==='--清除--'){
				$dp.find('.dropdown-toggle span:first-child').text(label);
				clear = true;
				delete filters[num];
			}else{
				$dp.find('.dropdown-toggle span:first-child').text(name);
				filters[num] = {id: id, name: name, categoryNumber: num};
			}
			filterProducts(num, clear);
		})
		.affix({
		    offset: {
			    top: 100
		    }
		});
		
		setTimeout(function(){
			getProducts(modelId);
		});
	}
	
	var w = $('.container').width()-parseInt($('.main-content').css('margin-left'));
	$('.main-content').css('width', w);
	$('.filter-bar').css('width', w + 2);
});